import { useMemo, useRef } from 'react'
import style from './index.module.less'
import { AddOutline, CloseCircleFill } from 'antd-mobile-icons'
import classNames from 'classnames'
import { getFilePath } from '@src/assets/js/tool'


function File ({ data, index, list, onChange }) {
  const path = useMemo(() => {
    return data ? getFilePath(data) : ''
  }, [data])
  return (
    <div className={style.item}>
      <div className={style['item-inner']}>
        {
          !path ? (
            <span>{data.name}</span>
          ) : (
            <a href={path} target='_blank'>{data.original_filename || data.filename}</a>
          )
        }
      </div>
      <div className={style.del} onClick={() => {
        const l = [...list]
        l.splice(index, 1)
        onChange(l)
      }}>
        <CloseCircleFill />
      </div>
    </div>
  )
}

function Main ({ value = [], onChange = () => {}, max = 9 }) {
  const ref = useRef()
  return (
    <div className={style.container}>
      <div className={style.list}>
        {
          value.map((v, i) => {
            return <File key={i} data={v} onChange={onChange} list={value} index={i} />
          })
        }
      </div>
      <label className={classNames(style.add, {[style.hide]: value.length >= max})}>
        <input type='file' ref={ref} multiple={false} className={style.file} onChange={e => {
          const f = e.target.files[0]
          if (f) {
            onChange([...value, f])
            ref.current.value = ''
          }
        }} />
        <span className={style['btn-bg']} />
        <span className={style['add-text']}>
          <AddOutline />
          <span>添加</span>
        </span>
      </label>
    </div>
  )
}

export default Main
